package com.stt.experiment.trynetty.server;

import com.stt.experiment.trynetty.server.config.ServerConfig;
import com.stt.experiment.trynetty.server.handler.WebSocketServerHandler;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelPipeline;
import io.netty.handler.codec.http.HttpObjectAggregator;
import io.netty.handler.codec.http.HttpServerCodec;
import io.netty.handler.codec.http.websocketx.WebSocketServerProtocolHandler;
import io.netty.handler.stream.ChunkedWriteHandler;
import io.netty.handler.timeout.ReadTimeoutHandler;
import io.netty.handler.timeout.WriteTimeoutHandler;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import io.netty.channel.socket.SocketChannel;

/**
 * 构建Handler处理流程
 */
@Component
public class ServerChannelInitializer extends ChannelInitializer<SocketChannel>{

    @Autowired
    private ServerConfig serverConfig;
    @Autowired
    private WebSocketServerHandler webSocketServerHandler;

    @Override
    protected void initChannel(SocketChannel socketChannel) throws Exception {
        // 添加各种功能handler，依次执行
        ChannelPipeline pipeline = socketChannel.pipeline();
        // HttpServerCodec: 将请求和应答的消息解码为HTTP消息
        pipeline.addLast(new HttpServerCodec());
        // HttpObjectAggregator: 将HTTP消息的多个部分合成一条完整的HTTP消息
        pipeline.addLast(new HttpObjectAggregator(serverConfig.getMaxContentLength()));
        // ChunckedWriteHandler: 处理大数据传输，支持异步写大数据流，不引起高内存消耗。
        pipeline.addLast(new ChunkedWriteHandler());
        pipeline.addLast(new ReadTimeoutHandler(serverConfig.getReadTimeout()));
        pipeline.addLast(new WriteTimeoutHandler(serverConfig.getWriteTimeout()));
        pipeline.addLast(new WebSocketServerProtocolHandler(serverConfig.getWebSocketPath()));

        // 添加自定义默认处理器
        pipeline.addLast(webSocketServerHandler);
    }
}
